/****************************************************
 * 													*
 * 					BanzaiP2P						*
 * 													*
 * Versione: 0.1.1									*
 * Autore: D'Annessa Marco							*
 * File: bootstrap.c								*
 ****************************************************/

#include "bootstrap.h"




int try_connection(char * peer_file, int max_peer, struct peer* temp){
	
	FILE *peer;
	peer = fopen(peer_file,"rb");	
	//struct peer *temp;
	
	
	
	char *set=":";
	char *token;
	char line[255];
	int count=0;
	int sockcreate=0;
	
	
	//temp = (struct peer*)malloc(sizeof(struct peer)*max_peer);
	memset((char *) &addrTCP, 0, sizeof(struct sockaddr));

	addrTCP.sin_family = AF_INET;
	addrTCP.sin_addr.s_addr = INADDR_ANY;
		
	
	fgets(line,255,peer);
	do{printf("t: %s",line);
		token = strtok(line,set);
		addrTCP.sin_addr.s_addr = inet_addr(token);
		token = strtok(NULL,set);
		addrTCP.sin_port = htons(atoi(token));
	
		if(sockcreate==0)
			temp[count].peersock = socket(AF_INET,SOCK_STREAM,0);
		
		if(connect(temp[count].peersock, (struct sockaddr *) &addrTCP,sizeof(addrTCP))<0){
			printf(" erro1re\n");
			sockcreate=1;
			}
	
		else{
			
			memset((char *) &temp[count], 0, sizeof(struct sockaddr));
			temp[count].peer_addr = addrTCP;
			temp[count].peernick= (char*)malloc(sizeof(token));
			strcpy(temp[count].peernick,token);
			count++;
			sockcreate=0;
			printf(" ok\n");
		}
			
	
		fgets(line,255,peer);
		
	}while( (strcmp(line,"#")!=0) && count<max_peer);
	
	fclose(peer);
	
	if(count==0)
		printf("no connessione!!!\n");//alternativa con web
	
	
	return count;
}

void write_peer(char *peer_file ,char *ip,int port){
	
	FILE *peer;
	char strtemp[255],str[8];
	peer = fopen(peer_file,"r+");
	
	fseek(peer,-1,SEEK_END);
	

	strcpy(strtemp,ip);
	strcat(strtemp,":");
	sprintf(str,"%d",port);
	strcat(strtemp,str); 
	strcat(strtemp,"\n");
	fputs(strtemp, peer);	
	strcpy(strtemp,"#");
	fputs(strtemp,peer);

	
	fclose(peer);
	
	
}